package com.autumn.jvm.jvm;

import java.io.FileInputStream;
import java.lang.reflect.Method;

/**
 * @author: Autumn
 * @describe:
 * @date: 2022/9/30 0030
 * @modified By:
 */
public class MyClassLoaderTest {
    static class MyClassLoader extends ClassLoader {
        private String classPath;

        public MyClassLoader(String classPath) {
            this.classPath = classPath;
        }

        private byte[] loadByte(String name) throws Exception {
            //name = name.replaceAll("\\.", "/");
            FileInputStream fis = new FileInputStream(classPath + "/" + name + ".class");
            int len = fis.available();
            byte[] data = new byte[len];
            fis.read(data);
            fis.close();
            return data;
        }

        @Override
        protected Class<?> findClass(String name) throws ClassNotFoundException {
            try {
                byte[] data = loadByte(name);
                // defineClass将一个字节数组转为Class对象，此字节数组是class文件读取后最终的字节数组
                return defineClass(name, data, 0, data.length);
            } catch (Exception e) {
                e.printStackTrace();
                throw new ClassNotFoundException();
            }
        }

        // 打破双亲委派机制，重写ClassLoader的loadClass方法，将委托上级类加载器的逻辑删除即可
        @Override
        protected Class<?> loadClass(String name, boolean resolve)
                throws ClassNotFoundException {
            synchronized (getClassLoadingLock(name)) {
                // First, check if the class has already been loaded
                Class<?> c = findLoadedClass(name);
                if (c == null) {
                    long t0 = System.nanoTime();

                    // If still not found, then invoke findClass in order
                    // to find the class.
                    long t1 = System.nanoTime();

                    /* if (!name.startsWith("com.autumn.jvm")) {
                        c = this.getParent().loadClass(name);
                    } else {
                        c = findClass(name);
                    } */

                    // this is the defining class loader; record the stats
                    sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0);
                    sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
                    sun.misc.PerfCounter.getFindClasses().increment();
                }
                if (resolve) {
                    resolveClass(c);
                }
                return c;
            }
        }

        public static void main(String[] args) throws Exception {
            // 初始化自定义类加载器，先初始化父类加载器ClassLoader，期间将自定义类加载器的上级类加载器设置为应用程序类加载器
            MyClassLoader myClassLoader = new MyClassLoader("D:/demo");
            // D盘创建多级目录：test/com/autumn/jvm，将User1类放入该目录
            Class clazz = myClassLoader.loadClass("com.autumn.jvm.jvm.User1");
            Object obj = clazz.newInstance();
            Method method = clazz.getDeclaredMethod("sout", null);
            method.invoke(obj, null);
            System.out.println(clazz.getClassLoader().getClass().getName());

            // 初始化自定义类加载器，先初始化父类加载器ClassLoader，期间将自定义类加载器的上级类加载器设置为应用程序类加载器
            MyClassLoader myClassLoader1 = new MyClassLoader("D:/demo1");
            // D盘创建多级目录：test/com/autumn/jvm，将User1类放入该目录
            Class clazz1 = myClassLoader1.loadClass("com.autumn.jvm.jvm.User1");
            Object obj1 = clazz1.newInstance();
            Method method1 = clazz1.getDeclaredMethod("sout", null);
            method1.invoke(obj1, null);
            System.out.println(clazz1.getClassLoader().getClass().getName());
        }
    }
}



